import {loading, hide, toast} from "./utils/showTip";


const URL_ALL = {
    'DEV': 'http://192.168.100.142:3999', // 开发
    'PRO': 'http://192.168.100.142:3999', // 生产
}

let BASEURL = URL_ALL['DEV'] // 调整当前环境

let TIME_OUT = 10000

/*
* 全局请求封装
* @param path 请求路径
* @param method 请求类型(GET/POST/DELETE等)
* @oaram data 请求体数据
* @param loading 请求未完成是是否显示加载中，默认为true
*/
export default (path, method, data = {}) => {
    // 获取存储token
    const token = uni.getStorageSync("token");

    //根据token进行调用函数
    if (token !== '') {
        return tokenRequest(path, method, data, token)
    } else {
        return noTokenRequest(path, method, data)
    }
};

// 无token时发送请求函数
function noTokenRequest(path, method, data) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: BASEURL + path,
            method: method,
            timeout: TIME_OUT,
            data,
            success(response) {
                // console.log('%c响应拦截：', ' background:green', response);
                /* if (response.data.code === 3001) {
                    // logout()
                } */
                /* if (response.data.code !== 20) {
                    uni.showToast({
                        icon: "none",
                        duration: 4000,
                        title: response.data.msg
                    });
                } */
                uni.setStorageSync('token', response.header.Authorization);
                console.log(uni.getStorageSync("token"))
                if (response.data.code === 65000) {
                    uni.reLaunch({url: '/pages/login/login'})
                }
                resolve(response.data);
            },
            fail(err) {
                toast('服务器开小差了', null, false, 1000)
                console.error(err);
                reject(err);
            },
            complete() {
                hide()
            }
        });
    });
}

// 有token时发送请求函数
function tokenRequest(path, method, data, token) {
    return new Promise((resolve, reject) => {
        uni.request({
            url: BASEURL + path,
            method: method,
            timeout: TIME_OUT,
            data,
            header: {
                "Authorization":  token
            },
            success(response) {
                if (response.data.code === 65000) {
                    uni.reLaunch({url: `/pages/login/login`})
                }
                resolve(response.data);
            },
            fail(err) {
                toast('服务器开小差了', null, false, 1000)
                console.error(err);
                reject(err);
            },
            complete() {
                hide()
            }
        });
    });
}
